package main

import (
	"flag"
	//"fmt"
	"gozerojpeg/internal"
	//"log"
	"net/http"

	_ "net/http/pprof"

	//"gocv.io/x/gocv"
	"github.com/tal-tech/go-zero/core/logx"
	"github.com/tal-tech/go-zero/core/service"
	"github.com/tal-tech/go-zero/rest"
)

var (
	port    = flag.Int("port", 3333, "the port to listen")
	timeout = flag.Int64("timeout", 0, "timeout of milliseconds")
	cpu     = flag.Int64("cpu", 500, "cpu threshold")
)

func main() {
	// open webcam
	//webcam, err = gocv.OpenVideoCapture("rtsp://admin:ranqi333@114.242.130.60:556/h264/ch1/sub/av_stream")
	//if err != nil {
	//	fmt.Printf("Error opening capture device: %v\n", deviceID)
	//	return
	//}
	//defer webcam.Close()
	//
	//
	//
	//// start capturing
	//go mjpegCapture()
	//
	//fmt.Println("Capturing. Point your browser to ")
	initWS()

}
func initWS() {
	flag.Parse()

	logx.Disable()
	engine := rest.MustNewServer(rest.RestConf{
		ServiceConf: service.ServiceConf{
			Log: logx.LogConf{
				Mode: "console",
			},
		},
		Port:         *port,
		Timeout:      *timeout,
		CpuThreshold: *cpu,
	})
	defer engine.Stop()

	hub := internal.NewHub()
	go hub.Run()
	engine.AddRoute(rest.Route{
		Method: http.MethodGet,
		Path:   "/",
		Handler: func(w http.ResponseWriter, r *http.Request) {
			if r.URL.Path != "/" {
				http.Error(w, "Not found", http.StatusNotFound)
				return
			}
			if r.Method != "GET" {
				http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
				return
			}

			http.ServeFile(w, r, "home.html")
		},
	})

	engine.AddRoute(rest.Route{
		Method: http.MethodGet,
		Path:   "/ws",
		Handler: func(w http.ResponseWriter, r *http.Request) {
			internal.ServeWs(hub, w, r)
		},
	})

	engine.Start()

}
func mjpegCapture() {
	//img := gocv.NewMat()
	//defer img.Close()
	//
	//for {
	//	if ok := webcam.Read(&img); !ok {
	//		fmt.Printf("Device closed: %v\n", deviceID)
	//		return
	//	}
	//	if img.Empty() {
	//		continue
	//	}
	//
	//	buf, _ := gocv.IMEncode(".jpg", img)
	//	//stream.UpdateJPEG(buf)
	//}
}
